package com.joeyzh.soundrecorder;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.joeyzh.soundrecorder.audio.AddAudioAdapter;
import com.joeyzh.soundrecorder.audio.AudioDialogFragment;
import com.joeyzh.soundrecorder.audio.AudioView;
import com.joeyzh.soundrecorder.bean.AudioModel;
import com.joeyzh.soundrecorder.utils.AudioPickerManager;
import com.joeyzh.soundrecorder.utils.PickerConfig;
import com.joeyzh.soundrecorder.widget.ExpandGridView;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * Created by Joey on 2017/9/4.
 */

public class AudioFragment extends Fragment implements AddAudioAdapter.OnItemClickLisener, AudioDialogFragment.OnAudioListener {

    protected static PickerConfig config;
    /**
     * 音频时长
     * 默认60秒
     */
    private static int countdownTime = 5;
    /**
     * 空音频
     */
    private final AudioModel emptyRecording = AddAudioAdapter.EmptyPath();
    protected AlertDialog dlgDelete;
    /**
     * 音频类型 默认为音频
     */
    private String AudioType = AudioPickerManager.Record;
    private ImageButton btnShowAudio;
    private View layoutAudio;
    private ExpandGridView gvAudios;
    private AddAudioAdapter addAdapter;
    private int MAX_NUM = 9;
    private TextView tvAudioCount;
    private boolean editable = true;
    private TextView tvPickerTitle;
    private View view;
    private ArrayList<AudioModel> audiosList = new ArrayList<>();
    private AudioModel deletePath;
    private boolean changed;
    private String title;
    private String IMAGE_VALUE = "音频";

    public AudioFragment() {
        config = new PickerConfig();
        setArguments(new Bundle());
    }


    public static AudioFragment newInstance(ArrayList<AudioModel> recordingPath) {
        return newInstance("", recordingPath);
    }

    public static AudioFragment newInstance(String title, ArrayList<AudioModel> recordingPath) {
        return newInstance(title, recordingPath, countdownTime);
    }

    /**
     * @param title         标题，如：音频附件
     * @param recordingPath 音频默认显示文件
     * @param countdownTime 音频默认时长
     * @return
     */
    public static AudioFragment newInstance(String title, ArrayList<AudioModel> recordingPath, int countdownTime) {
        AudioFragment submitFragment = new AudioFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putSerializable("records", recordingPath);
        bundle.putInt("countdownTime", countdownTime);
        submitFragment.setArguments(bundle);
        return submitFragment;
    }

    public static AudioFragment newInstance(String title) {
        return newInstance(title, countdownTime);
    }

    /**
     * @param title         标题，如：音频附件
     * @param countdownTime 音频默认时长
     * @return
     */
    public static AudioFragment newInstance(String title, int countdownTime) {
        AudioFragment submitFragment = new AudioFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putInt("countdownTime", countdownTime);
        submitFragment.setArguments(bundle);
        return submitFragment;
    }

    public AudioFragment initConfig(PickerConfig config) {
        if (config != null) {
            this.config = config;
        }
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.pictools_layout_image, null);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        switch (AudioType) {
            case AudioPickerManager.IMAGE_TYPE_HandwritingBoard:
                IMAGE_VALUE = "签名";
                break;
            case AudioPickerManager.IMAGE_TYPE:
                IMAGE_VALUE = "图片";
                break;
            case AudioPickerManager.Record:
                IMAGE_VALUE = "音频";
                break;
        }


        AudioView.DEFAULT_MIN_WIDTH = Integer.valueOf(getResources().getString(R.string.record_view_min_width));
        countdownTime = getArguments().getInt("countdownTime");

        MAX_NUM = config.getPickerMaxNum();
        btnShowAudio = view.findViewById(R.id.btn_show_image);
        tvPickerTitle = view.findViewById(R.id.tv_picker_title);
        layoutAudio = view.findViewById(R.id.layout_images);
        btnShowAudio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layoutAudio.getVisibility() == View.VISIBLE) {
                    hideAudios();
                } else {
                    showAudios();
                }
            }
        });
        gvAudios = view.findViewById(R.id.gv_submit_images);
        gvAudios.setNumColumns(config.getPickerNumColumns());
        tvAudioCount = view.findViewById(R.id.tv_submit_image_count);
        gvAudios.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isEqualsEmpty(audiosList.get(position))) {
                    if (!isEditable()) {
                        return;
                    }
                    final AudioDialogFragment fragment = AudioDialogFragment.newInstance(AudioDialogFragment.RECORD, countdownTime);
                    fragment.setOnAudioListener(AudioFragment.this);
                    fragment.show(getFragmentManager(), AudioDialogFragment.class.getSimpleName());
//                    fragment.setOnCancelListener(new RecordAudioDialogFragment2.OnAudioCancelListener() {
//                        @Override
//                        public void onCancel() {
//                            fragment.dismiss();
//                        }
//                    });
                    return;
                }
                // 跳转到详情
                gotoAudioDetail(position);

            }
        });
        gvAudios.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (!isEditable()) {
                    return true;
                }
                if (isEqualsEmpty(audiosList.get(position))) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        addAdapter = new AddAudioAdapter(getActivity(), audiosList);
        //实例化接口
        addAdapter.setCallback(this);
        audiosList.clear();
//        audiosList.add(AddAudioAdapter.EmptyPath());
        ArrayList<AudioModel> audios = (ArrayList<AudioModel>) getArguments().getSerializable("records");
        if (audios != null) {
            if (audios.size() >= MAX_NUM) {
                audiosList.clear();
            }
            audiosList.addAll(0, audios);
        }
        gvAudios.setAdapter(addAdapter);
        setEditable(editable);
        String tmpTitle = getArguments().getString("title");
        setTitle(tmpTitle);
    }

    public void gotoAudioDetail(int index) {
        ArrayList<AudioModel> audios = new ArrayList<>();
        if (audiosList.isEmpty())
            return;
        if (audiosList.size() == 1 && isEqualsEmpty(audiosList.get(0))) {
            return;
        }
        // 添加按钮在列表的第一个
        if (isEqualsEmpty(audiosList.get(audiosList.size() - 1))) {
            audios.addAll(audiosList.subList(0, audiosList.size() - 1));
        } else if (isEqualsEmpty(audiosList.get(0))) {
            // 添加按钮在列表的最后一个
            audios.addAll(audiosList.subList(1, audiosList.size()));
            index = index - 1;
        } else {
            // 没有添加按钮
            audios = audiosList;
        }
        //播放
        onPlay(audios.get(index));
//        Intent intent = new Intent(getActivity(), PhotosDisplayActivity.class);
//        intent.putExtra("index", index);
////     这段代码是因为传递base64大数据时，intent无法序列化传递    intent.putExtra("records", audios);
//        PhotosDisplayActivity.mapList = audios;
//        getActivity().startActivity(intent);
//     showDeleteDlg(audios.get(index));
    }

    public void showAudios() {
        Animation rotate = AnimationUtils.loadAnimation(getActivity(),
                R.anim.rotate_180);
        rotate.setFillAfter(true);
        btnShowAudio.startAnimation(rotate);
        layoutAudio.setVisibility(View.VISIBLE);
//        LogUtils.e("isEnabled : " + isEnabled());
    }


    public void hideAudios() {
        Animation rotate = AnimationUtils.loadAnimation(getActivity(),
                R.anim.rotate_ccw_180);
        rotate.setFillAfter(true);
        btnShowAudio.startAnimation(rotate);
        layoutAudio.setVisibility(View.GONE);
//        LogUtils.e("isEnabled : " + isEnabled());
    }

    public void setTitle(String title) {
        if (TextUtils.isEmpty(title)) {
            return;
        }
        this.title = title;
        if (tvPickerTitle != null)
            tvPickerTitle.setText(title);
    }

    public boolean isChanged() {
        return changed;
    }

    public void setChanged(boolean changed) {
        this.changed = changed;
    }

    public List<AudioModel> getImgsList() {
        if (audiosList.isEmpty()) {
            return audiosList;
        }
        int start = 0;
        int end = audiosList.size();
        if (isEqualsEmpty(audiosList.get(0))) {
            start = 1;
        } else if (isEqualsEmpty(audiosList.get(size() - 1))) {
            end = audiosList.size() - 1;
        }
        return audiosList.subList(start, end);
    }


    public AddAudioAdapter getAddAdapter() {
        return addAdapter;
    }

    public void addPath(AudioModel image) {
        int size = 0;
        if (audiosList.size() > 0) {
            size = audiosList.size() - 1;
        }
        audiosList.add(size, image);
        setAudioCount();
    }

    public void addPathList(Collection<AudioModel> pathArray) {
        int size = 0;
        if (audiosList.size() > 0) {
            size = audiosList.size() - 1;
        }
        if (pathArray.size() == 1) {
            audiosList.add(size, ((ArrayList<AudioModel>) pathArray).get(0));
        } else {
            audiosList.addAll(size, pathArray);
        }
        setAudioCount();
    }

    public void addPathList(int index, Collection<AudioModel> pathArray) {
        audiosList.addAll(index, pathArray);
        setAudioCount();
    }

    public TextView getTitleView() {
        return tvPickerTitle;
    }

    public void remove(AudioModel path) {
        audiosList.remove(path);
    }

    public void remove(int index) {
        audiosList.remove(index);
    }

    public void clear() {
        audiosList.clear();
        if (isEditable()) {
            audiosList.add(emptyRecording);
        }
    }

    public int size() {
        return audiosList.size();
    }

    private void showDeleteDlg(AudioModel path) {
        deletePath = path;
        dlgDelete = new AlertDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage(String.format("您确定要删除%s吗？", IMAGE_VALUE))
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setChanged(true);
                        if (audiosList.size() == MAX_NUM) {
                            if (!isEqualsEmpty(audiosList.get(MAX_NUM - 1)))
                                audiosList.add(MAX_NUM, emptyRecording);
                        }
                        audiosList.remove(deletePath);
                        setAudioCount();
                        addAdapter.notifyDataSetChanged();
                    }
                })
                .create();
        dlgDelete.show();
    }

    public void setAudioCount() {
        int size = audiosList.size();
        if (editable) {
            size = audiosList.size() - 1;
            if (size == MAX_NUM - 1) {
                size = (audiosList.contains(emptyRecording)) ? size : MAX_NUM;
            }
        }
        String message = String.format("已选择%s%d/%d", IMAGE_VALUE, size, MAX_NUM);
        if (size < 0) {
            message = "无";
        }
        if (tvAudioCount != null)
            tvAudioCount.setText(message);

        //显示音频
        showAudios();
    }

    public boolean isEditable() {
        return editable;
    }

    public void setEditable(boolean editable) {
        this.editable = editable;
        if (addAdapter == null) {
            return;
        }
        addAdapter.setEditable(editable);
        if (editable) {
            if (!audiosList.contains(emptyRecording)) {
                if (audiosList.size() < MAX_NUM)
                    audiosList.add(emptyRecording);
                setAudioCount();
                addAdapter.notifyDataSetChanged();
            }
        } else {
            audiosList.remove(emptyRecording);
            if (audiosList.isEmpty()) {
                hideAudios();
            }
            setAudioCount();
            addAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 显示音频数量
     *
     * @param visibility
     */
    public void setAudioCountVisibility(int visibility) {
        tvAudioCount.setVisibility(visibility);
    }


//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode != Activity.RESULT_OK) {
//            return;
//        }
//        if (requestCode == 99) {
//            //添加签名数据
////            addPath(data.getData().getPath());
//        } else if (requestCode == 100) {
//            ArrayList<AudioModel> temp = (ArrayList<AudioModel>) data
//                    .getSerializableExtra(SelectPictureActivity.INTENT_SELECTED_PICTURE);
//            addPathList(temp);
//        }
//        if (size() > MAX_NUM) {
//            remove(emptyRecording);
//        }
////        setAudioCount();
//        addAdapter.notifyDataSetChanged();
//    }

    public void setAudioType(String imageType) {
        AudioType = imageType;
    }


    /**
     * 等于空
     *
     * @param item
     * @return
     */
    private boolean isEqualsEmpty(AudioModel item) {
        return item.getFilePath().equals(AddAudioAdapter.EMPTY_PATH);
    }

    @Override
    public void onDelete(AudioModel fileBean) {
        showDeleteDlg(fileBean);
    }

    @Override
    public void onPlay(AudioModel fileBean) {
        final AudioDialogFragment fragment = AudioDialogFragment.newInstance(AudioDialogFragment.PLAY, countdownTime, fileBean);
//        fragment.setOnAudioListener(AudioFragment.this);
        fragment.show(getFragmentManager(), AudioDialogFragment.class.getSimpleName());
//        PlaybackDialogFragment fragmentPlay = PlaybackDialogFragment.newInstance(fileBean);
//        fragmentPlay.show(getFragmentManager(), PlaybackDialogFragment.class.getSimpleName());
    }


    public void setCountdownTime(int countdownTime) {
        this.countdownTime = countdownTime;
    }

    @Override
    public void onAudioFile(AudioModel recordingModel) {
        if (null == recordingModel || null == recordingModel.getFilePath() || recordingModel.getFilePath().isEmpty()) {
            return;
        }
        addPath(recordingModel);
        if (size() > MAX_NUM) {
            remove(emptyRecording);
        }
        //刷新数据
        getAddAdapter().notifyDataSetChanged();
    }

    /**
     * 清空音频文件
     */
    public void clearAudioFile() {
        AudioModel.clearRecordingDirectory();
    }

}
